<template>
  <div class="library-container">
    <h2>图书馆服务</h2>
    
    <el-tabs v-model="activeTab">
      <el-tab-pane label="图书查询" name="search">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>图书检索</span>
            </div>
          </template>
          
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="检索类型">
              <el-select v-model="searchForm.type" placeholder="请选择">
                <el-option label="书名" value="title"></el-option>
                <el-option label="作者" value="author"></el-option>
                <el-option label="ISBN" value="isbn"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="关键词">
              <el-input v-model="searchForm.keyword" placeholder="请输入检索关键词"></el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="searchBooks" :loading="searchLoading">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
          
          <el-table :data="books" style="width: 100%" v-loading="tableLoading">
            <el-table-column prop="isbn" label="ISBN" width="150"></el-table-column>
            <el-table-column prop="title" label="书名" show-overflow-tooltip></el-table-column>
            <el-table-column prop="author" label="作者" width="150"></el-table-column>
            <el-table-column prop="publisher" label="出版社" width="150"></el-table-column>
            <el-table-column prop="stock" label="库存" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.stock > 0 ? 'success' : 'danger'">
                  {{ scope.row.stock > 0 ? scope.row.stock : '已借完' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="viewBookDetail(scope.row)">详情</el-button>
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="borrowBook(scope.row)" 
                  :disabled="scope.row.stock <= 0">
                  借阅
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            @current-change="handlePageChange"
            class="pagination">
          </el-pagination>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="我的借阅" name="myBooks">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>当前借阅</span>
              <el-button @click="refreshBorrowed">刷新</el-button>
            </div>
          </template>
          
          <el-table :data="borrowedBooks" style="width: 100%" v-loading="borrowLoading">
            <el-table-column prop="title" label="书名" show-overflow-tooltip></el-table-column>
            <el-table-column prop="author" label="作者" width="150"></el-table-column>
            <el-table-column prop="borrowDate" label="借阅日期" width="180"></el-table-column>
            <el-table-column prop="dueDate" label="应还日期" width="180"></el-table-column>
            <el-table-column prop="daysLeft" label="剩余天数" width="120">
              <template #default="scope">
                <span :style="{ color: scope.row.daysLeft < 3 ? 'red' : 'green' }">
                  {{ scope.row.daysLeft > 0 ? scope.row.daysLeft + ' 天' : '已逾期' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="renewBook(scope.row)">续借</el-button>
                <el-button size="small" type="danger" @click="returnBook(scope.row)">归还</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <span>借阅历史</span>
            </div>
          </template>
          
          <el-table :data="borrowHistory" style="width: 100%">
            <el-table-column prop="title" label="书名" show-overflow-tooltip></el-table-column>
            <el-table-column prop="author" label="作者" width="150"></el-table-column>
            <el-table-column prop="borrowDate" label="借阅日期" width="180"></el-table-column>
            <el-table-column prop="returnDate" label="归还日期" width="180"></el-table-column>
          </el-table>
          
          <el-pagination
            layout="prev, pager, next"
            :total="historyTotal"
            :page-size="historyPageSize"
            @current-change="handleHistoryPageChange"
            class="pagination">
          </el-pagination>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 图书详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="selectedBook.title" width="50%">
      <el-form :model="selectedBook" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="ISBN:">
              <span>{{ selectedBook.isbn }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者:">
              <span>{{ selectedBook.author }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版社:">
              <span>{{ selectedBook.publisher }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版日期:">
              <span>{{ selectedBook.publishDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="页数:">
              <span>{{ selectedBook.pages }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存:">
              <el-tag :type="selectedBook.stock > 0 ? 'success' : 'danger'">
                {{ selectedBook.stock > 0 ? selectedBook.stock : '已借完' }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="简介:">
              <span>{{ selectedBook.description }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            @click="borrowBook(selectedBook)" 
            :disabled="selectedBook.stock <= 0">
            {{ selectedBook.stock > 0 ? '借阅' : '已借完' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Library',
  data() {
    return {
      activeTab: 'search',
      searchForm: {
        type: 'title',
        keyword: ''
      },
      searchLoading: false,
      tableLoading: false,
      borrowLoading: false,
      books: [
        {
          id: 1,
          isbn: '9787111598734',
          title: 'Java核心技术 卷I',
          author: 'Cay S. Horstmann',
          publisher: '机械工业出版社',
          publishDate: '2020-01-01',
          pages: 687,
          stock: 3,
          description: '《Java核心技术》出版以来，一直备受广大Java 程序员的青睐。'
        },
        {
          id: 2,
          isbn: '9787115560105',
          title: 'Vue.js设计与实现',
          author: '霍春阳',
          publisher: '人民邮电出版社',
          publishDate: '2021-04-01',
          pages: 484,
          stock: 0,
          description: '本书从Vue.js框架的设计思想入手，深入分析Vue.js源码。'
        },
        {
          id: 3,
          isbn: '9787115471646',
          title: '算法导论',
          author: 'Thomas H. Cormen',
          publisher: '机械工业出版社',
          publishDate: '2018-12-01',
          pages: 1288,
          stock: 2,
          description: '本书提供了对当代计算机算法研究的一个全面、综合性的介绍。'
        }
      ],
      total: 100,
      pageSize: 10,
      currentPage: 1,
      borrowedBooks: [
        {
          id: 1,
          title: '深入理解计算机系统',
          author: 'Randal E. Bryant',
          borrowDate: '2024-10-01 10:30:00',
          dueDate: '2024-10-28 23:59:59',
          daysLeft: 7
        },
        {
          id: 2,
          title: '设计模式：可复用面向对象软件的基础',
          author: 'Gang of Four',
          borrowDate: '2024-09-25 14:20:15',
          dueDate: '2024-10-22 23:59:59',
          daysLeft: 1
        }
      ],
      borrowHistory: [
        {
          title: '数据结构与算法分析',
          author: 'Mark Allen Weiss',
          borrowDate: '2024-09-01 09:15:30',
          returnDate: '2024-09-28 16:45:22'
        },
        {
          title: '计算机网络：自顶向下方法',
          author: 'James F. Kurose',
          borrowDate: '2024-08-15 11:30:45',
          returnDate: '2024-09-12 14:20:10'
        }
      ],
      historyTotal: 50,
      historyPageSize: 10,
      historyCurrentPage: 1,
      detailDialogVisible: false,
      selectedBook: {}
    }
  },
  methods: {
    async searchBooks() {
      this.searchLoading = true
      this.tableLoading = true
      
      try {
        // 模拟搜索延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        this.$message.success('搜索完成')
      } catch (error) {
        this.$message.error('搜索失败')
      } finally {
        this.searchLoading = false
        this.tableLoading = false
      }
    },
    resetSearch() {
      this.searchForm.keyword = ''
    },
    handlePageChange(page) {
      this.currentPage = page
      this.tableLoading = true
      // 模拟分页加载
      setTimeout(() => {
        this.tableLoading = false
      }, 500)
    },
    viewBookDetail(book) {
      this.selectedBook = book
      this.detailDialogVisible = true
    },
    async borrowBook(book) {
      if (book.stock <= 0) {
        this.$message.warning('该图书已借完')
        return
      }
      
      try {
        // 模拟借阅过程
        await new Promise(resolve => setTimeout(resolve, 1000))
        book.stock--
        this.$message.success(`《${book.title}》借阅成功！`)
        this.detailDialogVisible = false
      } catch (error) {
        this.$message.error('借阅失败，请稍后重试')
      }
    },
    async renewBook(book) {
      try {
        // 模拟续借过程
        await new Promise(resolve => setTimeout(resolve, 1000))
        book.daysLeft += 15
        book.dueDate = this.addDays(book.dueDate, 15)
        this.$message.success(`《${book.title}》续借成功，延长15天！`)
      } catch (error) {
        this.$message.error('续借失败，请稍后重试')
      }
    },
    async returnBook(book) {
      this.$confirm(`确定要归还《${book.title}》吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 模拟归还过程
          await new Promise(resolve => setTimeout(resolve, 1000))
          this.$message.success(`《${book.title}》归还成功！`)
          // 从当前借阅中移除
          const index = this.borrowedBooks.findIndex(b => b.id === book.id)
          if (index > -1) {
            this.borrowedBooks.splice(index, 1)
          }
        } catch (error) {
          this.$message.error('归还失败，请稍后重试')
        }
      }).catch(() => {
        // 取消操作
      })
    },
    refreshBorrowed() {
      this.borrowLoading = true
      // 模拟刷新数据
      setTimeout(() => {
        this.borrowLoading = false
        this.$message.success('刷新成功')
      }, 500)
    },
    handleHistoryPageChange(page) {
      this.historyCurrentPage = page
      // 模拟分页加载
      setTimeout(() => {
        this.$message.success('历史记录加载完成')
      }, 500)
    },
    addDays(date, days) {
      const result = new Date(date)
      result.setDate(result.getDate() + days)
      return result.toISOString().slice(0, 19).replace('T', ' ')
    }
  }
}
</script>

<style scoped>
.library-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.history-card {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>